package product

import (
	"context"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/util/gconv"
	"home-butler/internal/dao"
	"home-butler/internal/model"
	"home-butler/internal/model/do"
	"home-butler/internal/service"
	"home-butler/utility"
)

func init() {
	service.RegisterProductTopic(NewProductTopic())
}

type sProductTopic struct{}

func NewProductTopic() service.IProductTopic {
	return &sProductTopic{}
}

func (s sProductTopic) ListProductTopic(ctx context.Context, req *model.ProductTopicListReq) (res []*model.ProductTopicPageRes, err error) {
	q := dao.ProductTopic.Ctx(ctx)
	if req.Topic != "" {
		q.Where(dao.ProductTopic.Columns().Topic, req.Topic)
	}
	if req.ProductId != 0 {
		q.Where(dao.ProductTopic.Columns().ProductId, req.ProductId)
	}
	err = q.Scan(&res)
	if err != nil {
		return nil, err
	}
	return
}

func (s sProductTopic) CreateProductTopic(ctx context.Context, req *model.ProductTopicReq) (res *model.ProductTopicRes, err error) {
	productTopic := do.ProductTopic{}
	if err = gconv.Struct(req, &productTopic); err != nil {
		panic(err)
	}
	productTopic.Id = utility.GID.Generate().Int64()
	if _, err = dao.ProductTopic.Ctx(ctx).Insert(productTopic); err != nil {
		panic(err)
	}
	return
}

func (s sProductTopic) UpdateProductTopic(ctx context.Context, req *model.ProductTopicUpdateReq) (res *model.ProductTopicRes, err error) {
	if _, err := dao.ProductTopic.Ctx(ctx).Data(g.Map{
		dao.ProductTopic.Columns().Topic: req.Topic,
		dao.ProductTopic.Columns().Type:  req.Type,
	}).Where(dao.ProductTopic.Columns().Id, req.Id).Update(); err != nil {
		panic(err)
	}
	return
}

func (s sProductTopic) DelProductTopic(ctx context.Context, req *model.ProductTopicDelReq) (res *model.ProductTopicRes, err error) {
	if _, err := dao.ProductTopic.Ctx(ctx).Delete(dao.ProductTopic.Columns().Id, req.Id); err != nil {
		panic(err)
	}
	return
}
